package first.progr.helpstaff;

import static org.junit.Assert.fail;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;

public abstract class HelperBase {

	protected ApplicationManager manager;
	protected WebDriver driver;
	protected boolean acceptNextAlert = true;

	public HelperBase(ApplicationManager manager){
		this.manager = manager;
		this.driver = manager.driver;
	}
	
	public boolean isElementPresent(By by) {
	    try {
	    	driver.findElement(by);
	      return true;
	    } catch (NoSuchElementException e) {
	      return false;
	    }
	  }

	public boolean isAlertPresent() {
	    try {
	    	driver.switchTo().alert();
	      return true;
	    } catch (NoAlertPresentException e) {
	      return false;
	    }
	  }

	public String closeAlertAndGetItsText() {
	    try {
	      Alert alert = driver.switchTo().alert();
	      String alertText = alert.getText();
	      if (acceptNextAlert) {
	        alert.accept();
	      } else {
	        alert.dismiss();
	      }
	      return alertText;
	    } finally {
	    	acceptNextAlert = true;
	    }
	  }

	protected void findAndEnter(By locator, String info) {
		if (info != null) {
		  driver.findElement(locator).clear();
		  driver.findElement(locator).sendKeys(info);
	    }
	}
	
	protected void findAndSelect(By locator, String info) {
		if (info != null) {
		  new Select(driver.findElement(locator)).selectByVisibleText(info);
	    }
	}
	
	protected void findAndClick(By locator) {
		driver.findElement(locator).click();
	}

	protected void waitElement(By locator) throws InterruptedException {
		for (int second = 0;; second++) {
		  	if (second >= 60) fail("timeout");
		    try {
			if (isElementPresent(locator)) break; } catch (Exception e) {}
		    Thread.sleep(1000);
		  }
	}
	
	public HelperBase msBoxPresence() throws InterruptedException {
		waitElement(By.xpath("//div[@class='msgbox']"));
		return this;
	}
	
}
